package cn.sundat.web;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.sundat.model.Company;
import cn.sundat.model.ProductLink;
import cn.sundat.service.CompanyService;
import cn.sundat.service.ProductLinkService;
import cn.sundat.utils.FastJsonUtils;


public class ProductLinkAction extends ActionSupport implements ModelDriven<ProductLink>{
	@Resource(name="productLinkService")
	private ProductLinkService productLinkService;
	
	@Resource(name="companyService")
	private CompanyService companyService;
	
	private ProductLink productLink = new ProductLink();
	
	@Override
	public ProductLink getModel() {
		return productLink;
	}
	
	public String save() {
		productLinkService.save(productLink);
		return NONE;
	}
	
	private String comp_id;
	
	public String getComp_id() {
		return comp_id;
	}
	
	public void setComp_id(String comp_id) {
		this.comp_id = comp_id;
	}
	
	/**
	 * 根据公司的id查找公司的联系人
	 * @return 公司联系人集合的json字符串
	 */
	public String findAll() {
		Company company = companyService.getById(comp_id);
		List<ProductLink>  list = productLinkService.findAll(company);
		String jsonString = FastJsonUtils.toJsonString(list);
		HttpServletResponse response = ServletActionContext.getResponse();
		FastJsonUtils.write_json(response, jsonString);
		return NONE;
	}
	
	public String getById() {
		String link_id = productLink.getLink_id();
		System.out.println(link_id);
		ProductLink product = productLinkService.getById(link_id);
		String jsonString = FastJsonUtils.toJsonString(product);
		HttpServletResponse response = ServletActionContext.getResponse();
		FastJsonUtils.write_json(response, jsonString);
		return NONE;
	}
	/**
	 * 添加或者修改
	 * @return
	 */
	public String update() {
		//根据id获取该联系人信息
		ProductLink link = productLinkService.getById(productLink.getLink_id());
		//设置新的参数
		link.setLink_sex(productLink.getLink_sex());
		link.setLink_name(productLink.getLink_name());
		link.setLink_phone(productLink.getLink_phone());
		link.setLink_email(productLink.getLink_email());
		System.out.println("link"+link);
		//调用业务层方法
		productLinkService.update(link);
		return NONE;
	}
	
	public String delete() throws IOException {
		//根据id获取该联系人信息
		ProductLink link = productLinkService.getById(productLink.getLink_id());
		try {
			if(link!=null) {
				productLinkService.delete(link);
			}
		} catch (Exception e) {
			ServletActionContext.getResponse().getWriter().println("该联系人有负责产品，不能删除。");
		}
		return NONE;
	}
	
}
